<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends CI_Model {

	function __construct() {
        parent::__construct();
        self::initialize();
    }

    public function exists($username)
    {
    	$query = $this->db->query("SELECT `UserId` FROM `users` WHERE (`Username` LIKE " . $this->db->escape((string) $username) . ") LIMIT 1");

    	return ($query->num_rows() > 0);
    }

    public function getUser($username, $password) {
        $user = array(
                        'UserId' => 0,
                        'Username' => '',
                        'Password' => '',
                        'FirstName' => '',
                        'MiddleName' => '',
                        'LastName' => '',
                        'FullName' => '',
                        'Gender' => '',
                        'Email' => '',
                        'Role' => '',
                        'Privileges' => '',
                        'IsLoggedIn' => 0
                     );

        $sql = "SELECT\n" .
               "`UserId`, `Username`, `Password`, `FirstName`, `MiddleName`, `LastName`, CAST(CASE WHEN `Gender` LIKE 'B' THEN 'Brother' WHEN `Gender` LIKE 'S' THEN 'Sister' ELSE '' END AS char(10)) AS `Gender`, `Email`, `Role`, `Privileges`\n" .
               "FROM `users`\n" .
               "WHERE\n" .
               "(BINARY `Username` = BINARY " . $this->db->escape((string) $username) . ")";

        $query = $this->db->query($sql);

        if ($query->num_rows() > 0) {
            $row = $query->row_array();

            $pwd = $this->encrypt->decode($row['Password']);
            if ($pwd === $password) {
                $user = array(
                            'UserId' => $row['UserId'],
                            'Username' => $row['Username'],
                            'Password' => $password,
                            'FirstName' => $row['FirstName'],
                            'MiddleName' => $row['MiddleName'],
                            'LastName' => $row['LastName'],
                            'FullName' => substr($row['Gender'], 0, 3) . (trim($row['Gender']) != ''? '.' : '') . (trim($row['FirstName']) != '' || trim($row['LastName']) != ''? ' ' : '') . trim($row['FirstName']) . (trim($row['LastName']) != ''? ' ' : '') . trim($row['LastName']),
                            'Gender' => $row['Gender'],
                            'Email' => $row['Email'],
                            'Role' =>  $this->encrypt->decode($row['Role']),
                            'Privileges' => $row['Privileges'],
                            'IsLoggedIn' => 1
                         );    
            } 
        }
    
        return $user;
    }
	
	public function getIndividualUser($id) {
        $user = array(
                        'UserId' => 0,
                        'UserName' => '',
                        'FirstName' => '',
                        'LastName' => '',
                        'Email' => '',
                     );

        $sql = "SELECT\n" .
               "`UserId` AS `Id`, `UserName`, `FirstName`, `LastName`, `Email` " .
               "FROM `users`\n" .
               "WHERE\n" .
               "`UserId` = " . $id;

        $query = $this->db->query($sql);

        if ($query->num_rows() > 0) {
            $row = $query->row_array();

            $user = array(
                          'UserId' => $row['Id'],
                          'UserName' => $row['UserName'],
                          'FirstName' => $row['FirstName'],
                          'LastName' => $row['LastName'],
                          'Email' => $row['Email'],
                         );    
        }
    
        return $user;
    }
	
	public function getAll(){
	   	$sql = "SELECT " .
			   "UserId AS `Id`, " .
			   "UserName, " .
			   "LastName, " .
			   "FirstName, " .
			   "Email" .
			   "FROM " .
			   "users " .
			   "ORDER BY " .
			   "LastName, FirstName ASC";

		$query = $this->db->query($sql);
		return $query->result_array();
	}

    public function initialize() {
    	$configFile = SITE_PATH . 'config\default-users.xml';
        $sql = '';
        $defaultUsers = null;

    	if (file_exists($configFile))
    	{
            date_default_timezone_set(CURRENT_TIMEZONE);

            $url = base_url() . 'config/default-users.xml';
    		$defaultUsers = simplexml_load_file($url);

    		$this->db->trans_begin();

    		$privileges = '';
            
            for ($i = 0; $i < 500; $i++) $privileges .= '1';

    		foreach ($defaultUsers->defaultuser as $defaultUser) {
                if (!self::exists($defaultUser->username)) {
                    $data = array(
                                'Username' => (string) $defaultUser->username,
                                'Password' => $this->encrypt->encode($defaultUser->password),
                                'FirstName' => (string) $defaultUser->firstname,
                                'MiddleName' => (string) $defaultUser->middlename,
                                'LastName' => (string) $defaultUser->lastname,
                                'Gender' => (string) $defaultUser->gender,
                                'Role' => $this->encrypt->encode(SUPER_USER_ROLE),
                                'Privileges' => $privileges,
                                'Email' => (string) $defaultUser->email,
                                'IsEmailVerified' => 1,
                                'IsActive' => 1,
                                'DateCreated' => date("Y-m-d H:i:s")
                            );


                    $sql =  $this->db->insert_string('users', $data);
    				$this->db->query($sql); 
    			}
    		}

    		if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
            }
            else {
                $this->db->trans_commit();
            }
    	}
    }

    public function traineeExists($username, $traineeid) {
        $exists = false;

        $sql = "SELECT " .
               "u.`UserId` " .
               "FROM " .
               "`trainees` AS `t` " .
               "INNER JOIN `users` AS u ON t.UserId = u.UserId " .
               "WHERE " .
               "(u.Username LIKE " . $this->db->escape($username) . ")";

        if ($traineeid > 0) $sql .= " AND (t.TraineeId <> " . $traineeid . ")";

        $sql .= " UNION ALL " .
                "SELECT " .
                "u.`UserId` " .
                "FROM " .
                "`users` AS u " .
                "LEFT OUTER JOIN `trainees` AS t ON u.UserId = t.UserId " .
                "WHERE " .
                "(t.TraineeId IS NULL) AND " .
                "(u.Username LIKE " . $this->db->escape($username) . ")";

        $query = $this->db->query($sql);
        $exists = ($query->num_rows() > 0);
        
        return $exists;
    }

    public function usernameExists($username, $userid) {
        $exists = false;

        $sql = "SELECT `UserId` FROM `users` AS `u` WHERE (`Username` LIKE " . $this->db->escape($username) . ")";
        if ($userid > 0) $sql .= " AND (`UserId` <> " . $userid . ")";

        $query = $this->db->query($sql);
        $exists = ($query->num_rows() > 0);

        return $exists;
    }


}